package com.agilestudio.modules.orm.hibernate;

import java.util.Date;

import org.apache.commons.lang.ArrayUtils;
import org.hibernate.event.PreInsertEvent;
import org.hibernate.event.PreInsertEventListener;
import org.hibernate.event.PreUpdateEvent;
import org.hibernate.event.PreUpdateEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.agilestudio.ifinance.entity.IdEntity;

@SuppressWarnings("serial")
public class MyPreEventListener implements PreInsertEventListener,
		PreUpdateEventListener {

	protected Logger log = LoggerFactory.getLogger(getClass());

	public boolean onPreInsert(PreInsertEvent event) {
		log.info("onPreInsert ############");		
		if (event.getEntity() instanceof IdEntity) {
			IdEntity e = (IdEntity) event.getEntity();
			Date currentTime = new Date();
			e.setCreateTime(currentTime);
			String[] propertyNames = event.getPersister().getPropertyNames();
			Object[] state = event.getState();
			setValue(state, propertyNames, "createTime", currentTime, e);
		}
		return false;
	}

	public boolean onPreUpdate(PreUpdateEvent event) {
		log.info("onPreUpdate ############0");	
		if (event.getEntity() instanceof IdEntity) {
			IdEntity e = (IdEntity) event.getEntity();
			Date currentTime = new Date();
			e.setUpdateTime(currentTime);
			String[] propertyNames = event.getPersister().getPropertyNames();
			Object[] state = event.getState();
			setValue(state, propertyNames, "updateTime", currentTime, e);
		}
		return false;
	}

	private void setValue(Object[] currentState, String[] propertyNames,
			String propertyToSet, Object value, Object entity) {
		int index = ArrayUtils.indexOf(propertyNames, propertyToSet);
		if (index >= 0) {
			currentState[index] = value;
		} else {
			log.error("Field '" + propertyToSet + "' not found on entity '"
					+ entity.getClass().getName() + "'.");
		}
	}

	// @Override
	// public void onSaveOrUpdate(SaveOrUpdateEvent event) {
	// if (event.getEntity() instanceof IdEntity) {
	// IdEntity e = (IdEntity) event.getEntity();
	// Date currentTime = new Date();
	// if (e.getId() == null) {
	// e.setCreateTime(currentTime);
	// } else {
	// e.setUpdateTime(currentTime);
	// }
	// }
	// super.onSaveOrUpdate(event);
	// }

}
